package api

import (
	"blogdemo/gin/errmsg"
	"blogdemo/gin/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Login 用户登录
func Login(c *gin.Context) {
	var user model.User
	// 绑定数据模型
	_ = c.ShouldBind(&user)

	findUser := model.FindUser(user.Username)
	if !findUser {
		c.JSON(400, gin.H{
			"status": errmsg.USERNAME_INEXIST,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.USERNAME_INEXIST),
		})
		fmt.Println("用户名不存在")
		c.Abort()
		return
	}

	checklogin := model.CheckLogin(user.Username, user.Password)
	if checklogin == errmsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"status": errmsg.SUCCESS,
			"data":   user,
			"msg":    errmsg.GetErrMsg(errmsg.SUCCESS),
		})
		fmt.Println("登陆成功")
	} else {
		c.JSON(400, gin.H{
			"status": checklogin,
			"data":   user,
			"msg":    errmsg.GetErrMsg(checklogin),
		})
		fmt.Println("用户名或密码错误")
	}
	return
}
